package com.seecoder.BlueWhale.serviceImpl;

import com.seecoder.BlueWhale.annotation.RoleAccessCheck;
import com.seecoder.BlueWhale.enums.CouponStatusEnum;
import com.seecoder.BlueWhale.enums.CouponTypeEnum;
import com.seecoder.BlueWhale.enums.RoleEnum;
import com.seecoder.BlueWhale.po.Coupon;
import com.seecoder.BlueWhale.po.CouponGroup;
import com.seecoder.BlueWhale.repository.CouponGroupRepository;
import com.seecoder.BlueWhale.repository.CouponRepository;
import com.seecoder.BlueWhale.service.CouponService;
import com.seecoder.BlueWhale.util.SecurityUtil;
import com.seecoder.BlueWhale.vo.CouponVO;
import org.apache.xmlbeans.impl.common.NameUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CouponServiceImpl implements CouponService {
    @Autowired
    SecurityUtil securityUtil;
    @Autowired
    CouponRepository couponRepository;
    @Autowired
    CouponGroupRepository couponGroupRepository;

    @Override
    @RoleAccessCheck(role = RoleEnum.CUSTOMER)
    public List<CouponVO> getAllCoupons(int storeId, double price, List<CouponTypeEnum> chosenTypes) {
        return couponRepository.findAllByUserIdAndCouponStatus(securityUtil.getUserId(), CouponStatusEnum.UNUSED)
                .stream().map(Coupon::toVO).filter(couponVO -> {
                    CouponGroup couponGroup = couponGroupRepository.findById(couponVO.getCouponGroupId());
                    return (
                        (couponGroup.getCouponType() != CouponTypeEnum.FULL_REDUCTION ||
                         couponGroup.getFullAmount() <= price)
                        && (chosenTypes== null || !chosenTypes.contains(couponGroup.getCouponType()))
                        && (storeId == 0 || couponGroup.getStoreId() == 0 || couponGroup.getStoreId() == storeId)
                    );
                }).collect(Collectors.toList());
    }
}
